var tools = {
  token: "wOGy3WcrHS",
  // baseURL: 'http://dev.cnskycc.club',
  baseURL: 'http://qian.cnskycc.com',
  // baseURL: 'http://money.cnskycc.com',

  /**
   * localStorage
   * @param {*} key 
   * @param {*} value 
   */
  setItem: function(key, value) {
    if(typeof value === "object") {
      value = JSON.stringify(value)
    }
    localStorage.setItem(key, value)
    return true
  },

  /**
   * 获取 localStorage
   * @param {*} key 
   */
  getItem: function(key) {
    var value = localStorage.getItem(key)
    if(!value) return false
    try {
      return JSON.parse(value)
    } catch (error) {
      return value
    }
  },

  /**
   * 清除某项 localStorage
   * @param {*} key 
   */
  removeItem: function(key) {
    return localStorage.removeItem(key)
  },

  /**
   * 设置默认请求参数
   * @param {*} options 
   */
  setParams: function(options) {
    options.url = this.baseURL + options.url;
    var ui = tools.getItem('userInfo');
    var token = ui ? ui.token : null;
    token = token ? token.slice(0, token.length - tools.token.length) : null
    var headers = token ? { authorization: "Bearer " + token } : {};
    return $.extend(true, {}, {
      type: 'GET',
      timeout: 10000,
      dataType: 'json',
      headers: headers,
      error: function(err) {
        if(err.status === 403) {
          tools.removeItem('userInfo');
          tools.wxLogin();
        }
      }
    }, options)
  },

  /**
   * ajax 请求
   * @param {*} options 
   */
  ajax: function(options) {
    var params = tools.setParams(options)
    $.ajax(params)
  },

  /**
   * 获取微信授权接口
   */
  initWX: function() {
    tools.ajax({
      url: `/index/index/js_api`,
      data: {
        url: location.href
      },
      success: function(res) {
        wx.config(JSON.parse(res))
      }
    })
  },

  /**
   * 隐藏部分微信功能
   */
  hide: function() {
    wx.ready(function() {
      wx.hideMenuItems({
        menuList: [
          "menuItem:share:appMessage",
          "menuItem:share:timeline",
          "menuItem:share:qq",
          "menuItem:share:weiboApp",
          "menuItem:favorite",
          "menuItem:share:facebook",
          "menuItem:share:QZone",
          "menuItem:copyUrl",
          "menuItem:originPage",
          "menuItem:openWithQQBrowser",
          "menuItem:openWithSafari",
          "menuItem:share:email",
          "menuItem:share:brand",
          "menuItem:readMode",
          "menuItem:delete"
        ]
      });
    })
  },

  /**
   * 获取用户信息
   */
  getWXInfo: function() {
    tools.ajax({
      url: '/index/index/oauth_callback',
      success: function(res) {
        if(res.code === 0) {
          tools.setItem('userInfo', res.data)
        }
      }
    })
  },

  /**
   * 微信登录
   * @param {*} url back的url
   */
  wxLogin: function(url) {
    tools.removeItem('userInfo');
    tools.ajax({
      url: '/index/index/oauth',
      data: { url: location.href },
      success: function(res) {
        if(res.code === 0) {
          window.location.href = res.redirect_url
        }
      }
    })
  },

  /**
   * 微信授权登录
   * @param {*} code 
   * @param {*} callback 
   */
  register: function(code, callback) {
    tools.ajax({
      url: '/index/index/user',
      data: { code: code },
      success: function(res) {
        if(res.code === 0) {
          res.data.token += tools.token;
          tools.setItem('userInfo', res.data);
          setTimeout(function() {
            callback(res);
          }, 100);
        }
      }
    })
  },

  /**
   * 微信登录
   * @param {*} callback 
   */
  login: function(callback) {
    if(tools.getQueryString('code') && !tools.getItem("userInfo")) {
      // 当 url 中有 code 时，走 user 接口，获取信息
      tools.register(tools.getQueryString('code'), callback)
    } else {
      callback()
    }
  },

  /**
   * 分享
   * @param {*} options 
   */
  share: function(options) {
    var option = $.extend(true, {}, {
      title: "天空文化传播",
      desc: "全城有礼游戏 区域广告宣传",
      link: location.href.replace(/code=.*\&state=.*\&?/, ""),
      imgUrl: '../../static/AdminLTE/img/avatar.gif',
      success: function() {}
    }, options)
    wx.onMenuShareAppMessage(option);
    wx.onMenuShareTimeline(option);
  },

  /**
   * 分享到朋友圈（即将废弃）
   * @param {*} options 
   */
  shareTimeline: function(options) {
    var option = $.extend(true, {}, {
      title: "天空文化传播",
      link: location.href.replace(/code=.*\&state=.*\&?/, ""),
      imgUrl: '../../static/AdminLTE/img/avatar.gif',
      success: function() {}
    }, options)
    wx.onMenuShareTimeline(option)
  },

  /**
   * 分享给好友（即将废弃）
   * @param {*} options 
   */
  shareAppMessage: function(options) {
    var option = $.extend(true, {}, {
      title: "天空文化传播",
      desc: "全城有礼游戏 区域广告宣传",
      link: location.href.replace(/code=.*\&state=.*\&?/, ""),
      imgUrl: '../../static/AdminLTE/img/avatar.gif',
      success: function() {}
    }, options)
    wx.onMenuShareAppMessage(option);
  },

  /**
   * 根据 key 获取 url 中的 value
   * @param {*} key 
   */
  getQueryString: function(key) {
		var url = window.location.search;
		var reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)");
		var result = url.substr(1).match(reg);
		return result ? decodeURIComponent(result[2]) : null;
  },

  /**
   * 日期过滤器
   * @param {*} time 
   * @param {*} format 
   */
  filterTime: function(time, format) {
    format = format || 'yyyy-MM-dd hh:mm:ss';
    if(!time) return
    var date = new Date(parseInt(time)*1000);

    if(/(y+)/.test(format)) {
      format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    var dt = {
      'M+': date.getMonth() + 1,
      'd+': date.getDate(),
      'h+': date.getHours(),
      'm+': date.getMinutes(),
      's+': date.getSeconds()
    }

    for(var key in dt) {
      if(new RegExp(`(${key})`).test(format)) {
        var str = dt[key] + ''
        format = format.replace(RegExp.$1,
          (RegExp.$1.length === 1) ? str : ('00' + str).substr(str.length)
        );
      }
    }
    return format;
  },

  /**
   * 格式化数字
   * @param {*} num 
   */
  filterNumber: function(num) {
    if(num >= 100000000) {
      return (num / 100000000).toFixed(2) + '亿'
    } else if(num >= 10000) {
      return (num / 10000).toFixed(2) + '万'
    } else {
      return num
    }
  }
}

// 初始化微信接口
tools.initWX();

// var vConsole = new VConsole();
